from database import SessionLocal, Base, engine
from student import crud
from fastapi import Depends, HTTPException, APIRouter
from sqlalchemy.orm import Session
import schema
import uvicorn

stu_api = APIRouter()


'''
session 的链接创建构成一个依赖项
是一个嵌套依赖：需要的返回一个Sessionlocal的对象，用后销毁
传递Sessionlocal对象传递给crud层

return 执行结束后函数完全结束
yield：在函数调用后还会继续执行
'''

'''
实现每一个db对话使用完之后都返回
'''


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 直接查询整个表
@stu_api.get("/", summary="直接返回整个表")
def get_all_students(db: Session = Depends(get_db)):
    return crud.get_student_all(db)


# 按照名字查询
@stu_api.get("/student/{name}", summary="按照名字查询数据库中的信息")
def get_students_by_name(name: str, db: Session = Depends(get_db)):
    return crud.get_student_by_stuname(db=db, stuname=name)


# 新增一个学生
@stu_api.post("/student/add/", summary="新增一个学生")
def get_students_by_name(student: schema.Student, db: Session = Depends(get_db)):
    # 先判断该学生是否存在
    stu_exist = crud.get_student_by_stuid(db, student.student_id)
    if stu_exist:
        crud.delete_student(db, student.student_id)
        return {"message": "学生已经存在"}
    # 计算学生id
    return crud.add_student(db, student)


# 更新一个学生
@stu_api.post("/student/update/", summary="按照学生姓名更新信息")
def update_students_by_name(student: schema.Student, db: Session = Depends(get_db)):
    # 先判断该学生是否存在
    stu_exist = crud.get_student_by_stuid(db, student.student_id)
    if not stu_exist:
        raise HTTPException(status_code=400, detail=f"学生编号 {student.student_id} 不存在")
    return crud.update_student(db, student)











# 删除一个学生
@stu_api.post("/student/delete/", summary="按照学生姓名删除信息")
def delete_students_by_name(stu_name: str, db: Session = Depends(get_db)):
    # 先判断该学生是否存在
    stu_exist = crud.get_student_by_stuname(db, stu_name)
    if not stu_exist:
        raise HTTPException(status_code=400, detail=f"学生姓名 {stu_name} 不存在")
    return crud.delete_student(db, stu_name)


'''
班级操作
'''


# 直接查询整个班级表
@stu_api.get("/class/", summary="直接返回整个班级表")
def get_all_class(db: Session = Depends(get_db)):
    return crud.get_class_all(db)
#
#
# 按照id查询班级
@stu_api.get("/class/class_search", summary="按照班级编号查询班级")
def get_class_by_id(class_id: str, db: Session = Depends(get_db)):
    return crud.get_class_by_id(db=db, id=class_id)

#
# 新增一个班级
@stu_api.post("/class/add/", summary="新增一个班级")
def get_students_by_name(str_class: schema.stu_class, db: Session = Depends(get_db)):
    # 先判断该班级是否存在
    class_exist = crud.get_class_by_id(db, str_class.class_id)
    if class_exist:
        return {"message": "班级已经存在"}
    return crud.add_class(db, str_class)


if __name__ == '__main__':
    uvicorn.run("controller:app", host="localhost", port=8000, reload=True)
